checkInputValue = function (e) {
    if (!$('#projectName').val()) {
        $('#projectName').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#projectName').parent().parent().removeClass('has-error')
    }

    if (!$('#projectUrl').val()) {
        $('#projectUrl').parent().parent().addClass('has-error')

        return false;
    } else {
        $('#projectUrl').parent().parent().removeClass('has-error')
    }

    if (!$('#keyword').val()) {
        $('#keyword').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#keyword').parent().parent().removeClass('has-error')
    }


    if (!$('#planner').val()) {
        $('#planner').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#planner').parent().parent().removeClass('has-error')
    }

    if (!$('#designer').val()) {
        $('#designer').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#designer').parent().parent().removeClass('has-error')
    }

    if (!$('#word').val()) {
        $('#word').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#word').parent().parent().removeClass('has-error')
    }

    if (!$('#fe').val()) {
        $('#fe').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#fe').parent().parent().removeClass('has-error')
    }

    if (!$('#be').val()) {
        $('#be').parent().parent().addClass('has-error')
        return false;
    } else {
        $('#be').parent().parent().removeClass('has-error')
    }
    return true;
}

// 确定上传所有信息
$('#uploadAll').click(function (e) {
    e.preventDefault();

    // 检查输入
    if (!checkInputValue()) {
        alert('信息填写不完整，无法上传')
        return;
    }

    // 检测文件是否有三个
    if (fileList.length > 3 || fileList.length <= 0) {
        alert('图片数量过多或过少')
        return;
    }

    var formData = new FormData();

    // formData.append("upload_file", convertBase64UrlToBlob(base64, fileType), filename);
    // formData.append("token", localStorage.getItem('local_token'));

    var xhr = new XMLHttpRequest();
    xhr.open('POST', remoteUrl + "/admin/matrixbox/upload", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            alert('提交成功')
        }
    }

    // 发送数据
    var count = 0;
    for (var i = 0; i < fileList.length; i++) {
        var file = fileList[i];
        var filename = file.name || '';
        var fileType = file.type || '';

        var reader = new FileReader();
        // onload事件
        reader.onload = function (e) {
            count++;
            var base64 = e.target.result || this.result;
            formData.append("upload_file" + count, convertBase64UrlToBlob(base64, fileType), filename);

            if (count >= fileList.length) {
                formData.append("token", localStorage.getItem('local_token'));
                formData.append("name", $('#projectName').val());
                formData.append("href", $('#projectUrl').val());
                formData.append("keyword", $('#keyword').val());
                formData.append("planner", $('#planner').val());
                formData.append("FE", $('#fe').val());
                formData.append("BE", $('#be').val());
                formData.append("designer", $('#designer').val());
                formData.append("wenan", $('#word').val());
                xhr.send(formData);
            }
        };

        reader.readAsDataURL(file);
    }



})

var fileList = [];
$(document).ready(function () {
    Dropzone.options.myAwesomeDropzone = {
        maxFiles: 3,
        autoProcessQueue: false
    }
    // Dropzone.options.myAwesomeDropzone.maxFiles = 3;
    Dropzone.autoDiscover = false;
    var myDropzone = new Dropzone("#my-awesome-dropzone");
    myDropzone.on("addedfile", function (file) {
        if (fileList.length >= 3) {
            alert('最多上传三张图片！')
            return;
        }
        fileList.push(file);
    });

});

var remoteUrl;
if (window.location.origin === "http://wechat.juzhen05.com") {
    remoteUrl = "http://api.juzhen05.com";
} else {
    remoteUrl = "http://localhost:61337";
}

function fecthLogin(account, password, cb) {
    $.post(remoteUrl + '/admin/matrixbox/login', { cmd: 2, account: account, password: password }, function (data) {
        if (cb) cb(data);
    })
}

function fecthTable(cb, condition, offset, limit) {
    $.get(remoteUrl + '/admin/matrixbox/list', { cmd: 3, condition: condition, offset: offset, limit: limit, token: localStorage.getItem('local_token') }, function (data) {
        if (cb) cb(data);
    })
}

function updateToken() {
    $.post(remoteUrl + '/admin/matrixbox/updatetoken', { token: localStorage.getItem('local_token') }, function (results) {
        if (results.code) {
            localStorage.setItem('local_token', results.token);
            login();
        } else {
            alert(results.data)
        }
    })
}
updateToken();

function login(){
    $('#login').hide();
    $('#table').show();
    $('#uploadCaseInfo').show()
    // 获取表格数据
    fecthTable(function (data) {
        console.log(data);
        // 初始化表格
        dataCount = data.result.count;
        pageCount = Math.ceil(dataCount / 10); // 10/page
        initTable(data.result.list, data.result.comments);
    }, null, 0, 10);
}

var curPage = 0;
var dataCount = 0;
var pageCount = 0;
var initTable = function (dataList, comments) {
    var titleDom = document.createElement('tr');
    var str = "";
    for (var i = 0; i < comments.length; i++) {
        str += '<th>' + comments[i].Comment + '</th>';
    }
    titleDom.innerHTML = str;
    $('.ibox-content thead').append(titleDom);


    for (var j = 0; j < dataList.length; j++) {
        var tr = document.createElement('tr');
        str = "";
        for (var k in dataList[j]) {
            if (k == "headimgUrl") {
                str += '<td>' + '<img class="headimgUrl" src="' + dataList[j][k] + '" >' + '</td>';
            } else {
                str += '<td>' + dataList[j][k] + '</td>';
            }

        }
        tr.innerHTML = str;
        $('.ibox-content tbody').append(tr);
    }

    // 空值判断
    if (dataList.length <= 0) {
        $('.ibox-content thead').html('暂无数据')
    }

    $('#DataTables_Table_0_info').text('显示 ' + (curPage * 10 + 1) + ' 到 ' + (curPage * 10 + dataList.length) + ' 项，共 ' + dataCount + ' 项')
}

// 登陆
$('#loginBtn').click(function () {
    fecthLogin($('#loginUser').val(), $('#loginPasswd').val(), function (data) {
        if (data.code) {
            localStorage.setItem('local_token', data.token)
            login();
        } else {
            alert(data.msg);
        }

    });
})


// 下一页
$('#DataTables_Table_0_next').click(function () {
    // 检查是否能下一页
    if (curPage + 1 < pageCount) {

        fecthTable(function (data) {
            console.log(data);
            // 初始化表格
            curPage++;
            $('.ibox-content thead').empty();
            $('.ibox-content tbody').empty();
            initTable(data.result.list, data.result.comments);
        }, null, (curPage + 1) * 10, 10);
    } else {
        alert('已经到达最后页');
    }
})

// 上一页
$('#DataTables_Table_0_previous').click(function () {
    // 检查是否能下一页
    if (curPage - 1 > -1) {
        fecthTable(function (data) {
            console.log(data);
            // 初始化表格
            curPage--;
            $('.ibox-content thead').empty();
            $('.ibox-content tbody').empty();
            initTable(data.result.list, data.result.comments);
        }, null, (curPage - 1) * 10, 10);
    } else {
        alert('已经到达最后页');
    }
})


// 修改其中一行的数据
$('tbody').delegate('button', 'click', function (e) {
    var parent;

    if (e.target.localName === "span") {
        parent = e.target.parentElement.parentElement;
    } else {
        parent = e.target.parentElement;
    }

    var wcOpenid = parent.children[0].textContent;
    var point = prompt('请输入积分');
    fecthPoint(function (data) {
        if (data.code) {
            alert('修改成功')
            parent.children[parent.children.length - 3].textContent = point;
        } else {
            alert(data.msg);
        }
    }, wcOpenid, point)

})

// 搜索
$('.serchBtn').click(function () {
    var name = $('.serchInput').val();
    if (name) {
        fecthTable(function (data) {
            console.log(data);
            // 初始化表格
            $('.ibox-content thead').empty();
            $('.ibox-content tbody').empty();
            initTable(data.result.list, data.result.comments);
        }, { name: name }, 0, 100);
    } else {
        fecthTable(function (data) {
            console.log(data);
            // 初始化表格
            curPage = 0;
            $('.ibox-content thead').empty();
            $('.ibox-content tbody').empty();
            initTable(data.result.list, data.result.comments);
        }, null, 0, 10);
    }

})



// -------- 将以base64的图片url数据转换为Blob --------
function convertBase64UrlToBlob(urlData, filetype) {
    //去掉url的头，并转换为byte
    var bytes = window.atob(urlData.split(',')[1]);

    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    var i;
    for (i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }

    return new Blob([ab], { type: filetype });
}